<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="localOptType === 'view'"
          @click="handleAdd"
          v-hasPermi="['purchase:detail:add']"
        >新增</el-button>
        <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single || localOptType === 'view'"
          @click="handleUpdate"
          v-hasPermi="['purchase:detail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || localOptType === 'view'"
          @click="handleDelete"
          v-hasPermi="['purchase:detail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:detail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" align="center" prop="itemCode" />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="物料图片" align="left" prop="itemImgUrl">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.itemImgUrl" :src="scope.row.itemImgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" width="140">
        <template slot-scope="scope">
          <el-input-number :disabled="localOptType === 'view'"
            v-model="scope.row.quantity"
            :min="1"
            :controls="true"
            :precision="0"
            size="mini"
            @change="(value) => handleQuantityChange(value, scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:detail:edit']" :disabled="localOptType === 'view'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:detail:remove']" :disabled="localOptType === 'view'"
          >删除</el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleView(scope.row)"
              v-hasPermi="['purchase:detail:query']"
          >查看1</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购申请单明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购申请单ID" prop="purchaseRequestId">
              <el-input v-model="form.purchaseRequestId" placeholder="请输入采购申请单ID" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订购数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入订购数量"  :disabled="!isEdit"/>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="form.itemCode" placeholder="请输入产品编码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.itemName" placeholder="请输入产品名称" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="产品单位" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料图片" prop="itemImgUrl">
              <image-preview v-if="form.itemImgUrl" :src="form.itemImgUrl" :width="50" :height="50"/>
            </el-form-item>
          </el-col>
        </el-row>



        <el-row>

          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" placeholder="请输入规格型号" maxlength="100" disabled show-word-limit/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="采购物品截图" prop="screenShotUrl" label-width="110px">
              <template v-if="isEdit">
                <image-upload v-model="form.screenShotUrl" :limit="1"  />
              </template>
              <template v-else>
                <img v-if="form.screenShotUrl" :src="form.screenShotUrl" id="screenShotUrl1" style="width:40% ;height: 40%;" @click="zoomImage('screenShotUrl1')"/>
              </template>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="!isEdit"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/purchase/detail";
import ItemSelect from "@/components/itemSelect/index.vue";
export default {
  name: "Detail",
  components: { ItemSelect },
  props: {
    requestId: {
      type: [String, Number],
      required: true
    },
    optType: {
      type: String,
      required: true,
      default: 'add'
    },

  },
  computed: {
    isViewMode() {
      return this.optType === 'view';
    }
  },
  data() {
    return {
      tableId: 'purchaseDetailTable',
      isEdit:false,
      localOptType: this.optType,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请单明细表格数据
      detailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseRequestId:null,
        orderBy: 'created_at',
        orderType: 'asc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseRequestId: [
          { required: true, message: "采购申请单ID不能为空", trigger: "blur" }
        ],        quantity: [
          { required: true, message: "订购数量不能为空", trigger: "blur" }
        ],        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    zoomImage(idName) {
      console.log('父类调用',idName);
      var image = document.getElementById(idName);
      // image.style.width = "100%";
      // image.style.height = "100%";
      if (image.style.width === "100%") {
        // 图片已放大，还原为原始大小
        image.title="点击放大";
        image.style.width = "40%";
        image.style.height = "40%";

      } else {
        image.title="点击缩小";
        // 图片未放大，放大为全屏大小
        image.style.width = "100%";
        image.style.height = "100%";

      }
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.isEdit=true;
      this.localOptType = "view";
      getDetail(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看申请单详细信息";

      });
    },
    changeAndSave(handType){
      console.log('changeAndSave--',this.form);
      if(!this.form.id){
        console.log('新建');
        return false;
      }

    },

    // 物料选择弹出框
    onItemSelected(obj) {
      this.form.itemId = this.itemId;
      if (obj != undefined && obj != null) {
        obj.forEach(element => {
          // 检查是否已存在相同物料
          const existingItem = this.detailList.find(item => item.itemId === element.itemId);
          console.log('existingItem--',existingItem);
          if (existingItem) {
            this.$modal.msgError(`物料 ${element.itemName}(${element.itemCode}) 已存在，请勿重复添加`);
            return; // 跳过当前物料的添加
          }

          this.form.purchaseRequestId = this.requestId;
          this.form.itemId = element.itemId;
          this.form.itemCode = element.itemCode;
          this.form.itemName = element.itemName;
          this.form.bomItemSpec = element.specification;
          this.form.unitOfMeasure = element.unitOfMeasure;
          this.form.itemOrProduct = element.itemOrProduct;
          this.form.specification=element.specification;
          this.form.quantity = 1;
          this.form.enableFlag = 'Y';
          this.form.tabName = this.tabName;
          this.form.itemImgUrl=element.imgUrl;
          addDetail(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.getList();
          });
        });
      }
    },
    /** 查询采购申请单明细列表 */
    getList() {
      this.loading = true;
      this.queryParams.purchaseRequestId=this.requestId;
      listDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.isEdit = false;
      this.localOptType = this.optType;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        purchaseRequestId: null,specification:null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        productCode: null,
        productName: null,
        quantity: null,
        receivedQuantity: null,
        unitPrice: null,
        totalWithoutTax: null,
        taxRate: null,        totalWithTax: null,        paidAmount: null,        payableAmount: null,        remarks: null,        createdAt: null,        updatedAt: null,        createBy: null,        updateBy: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.isEdit=true;
      console.log('--重置==');
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
/*    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购申请单明细";
    },*/
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.tabName = this.tabName; // 设置表单中的 tabName
      this.$refs.itemSelect.showFlag = true;
      this.isEdit=true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购申请单明细";
      });
      this.isEdit=true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();

            });
          } else {
            addDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();

            });
          }
        }
        // 触发父组件的更新方法
        this.$emit('data-changed', this.requestId);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购申请单明细编号为"' + ids + '"的数据项？').then(function() {
        return delDetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.$emit('data-changed', this.requestId);
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/detail/export', {
        ...this.queryParams
      }, `detail_${new Date().getTime()}.xlsx`)
    },
    /** 数量变化时的处理函数 */
    handleQuantityChange(value, row) {
      const updateData = {
        id: row.id,
        quantity: value,
        purchaseRequestId: this.requestId
      };

      updateDetail(updateData).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
        // 触发父组件的更新方法
        console.log('--刷新父类', this.requestId);
        this.$emit('data-changed', this.requestId);
        console.log('调用完成');
      }).catch(() => {
        // 如果保存失败，回滚数量
        row.quantity = this.oldQuantity;
      });
    },
  }
};
</script>

<style scoped>
.el-input-number.el-input-number--mini {
  width: 130px;
}
</style>
